package com.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EchoProtocol implements Runnable {

	private static final int BUFSIZE = 32; // size (in bytes) of I/O buffer
	private Socket clntSock; // socket connect to client
	private Logger logger; // Server logger

	public EchoProtocol(Socket clntSock, Logger logger) {
		this.clntSock = clntSock;
		this.logger = logger;
	}

	public static void handleEchoClient(Socket clntSock, Logger logger) {
		try {

			// get the input and output i/o streams from socket
			InputStream in = clntSock.getInputStream();
			OutputStream out = clntSock.getOutputStream();

			int recvMsgSize; // size of received message
			int totalByteEchoed = 0; // Bytes received from client
			byte[] echoBuffer = new byte[BUFSIZE];
			// receive until client closes connection , indicated by -1
			while ((recvMsgSize = in.read(echoBuffer)) != -1) {

				out.write(echoBuffer, 0, recvMsgSize);
				totalByteEchoed += recvMsgSize;
			}
			logger.info("Client " + clntSock.getRemoteSocketAddress()
					+ ", ehoed " + totalByteEchoed + " byte. ");

		} catch (IOException e) {
			logger.log(Level.WARNING, "Exception in echo protocol ", e);
		} finally {
			try {
				clntSock.close();
			} catch (IOException e2) {
				// TODO: handle exception
			}
		}

	}

	@Override
	public void run() {
		handleEchoClient(clntSock, logger);

	}

}
